package com.my.core.plugin;

import java.util.List;
import java.util.Map;

import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.my.common.BaseModel;
import com.my.common.DictKeys;
import com.my.core.annotation.TableMapping;
import com.my.core.kit.ClassSearchKit;
import com.my.core.kit.ConfigKit;

/**
 * 扫描model上的注解，绑定model和table
 * 
 */
public class TablelPlugin implements IPlugin {

	protected final Log log = Log.getLog(getClass());

	private Map<String, ActiveRecordPlugin> arpMap;

	public TablelPlugin(Map<String, ActiveRecordPlugin> arpMap) {
		this.arpMap = arpMap;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean start() {
		String scanPaths = ConfigKit.getStr(DictKeys.config_model_scan_package,"");
		List<Class<? extends BaseModel>> modelClasses = ClassSearchKit.of(BaseModel.class).scanPackages(scanPaths).search();
		System.err.println(modelClasses.toString());
		// 循环处理自动注册映射
		for (Class model : modelClasses) {
			// 获取注解对象
			TableMapping tableMapping = (TableMapping) model
					.getAnnotation(TableMapping.class);
			
			// 获取映射属性
			String dataSourceName,tableName,pkName;
			if (tableMapping == null) {
				dataSourceName = DictKeys.db_config_main;
				tableName = model.getSimpleName().toLowerCase();
				pkName = DictKeys.db_config_default_pk;
			}else{
				dataSourceName = tableMapping.ds().trim();
				tableName = tableMapping.value().trim();
				pkName = tableMapping.pk().trim();
			}

			if (dataSourceName.equals("") || tableName.equals("")
					|| pkName.equals("")) {
				log.error(model.getName() + "注解错误，数据源、表名、主键名为空 。");
				break;
			}

			// 映射注册
			ActiveRecordPlugin arp = arpMap.get(dataSourceName);
			if (arp == null) {
				log.error(model.getName() + "ActiveRecordPlugin不能为null。");
				break;
			}
			arp.addMapping(tableName, pkName, model);
		}
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

}
